package com.clwl.supervise.superviseapp.service.liability;

import com.clwl.supervise.superviseapp.entity.base.DailySaveVo;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.ContentList;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.ItemList;
import com.clwl.supervise.superviseapp.entity.base.rectificationSituationData.RectificationSituationData;
import com.clwl.supervise.superviseapp.entity.risk.JgDynamicScoring;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.util.UserHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LiabilityService {
    @Autowired
    private JgLiabilityStandardMapper liabilityStandardMapper;
    @Autowired
    private JgLiabilityContentMapper contentMapper;
    @Autowired
    private JgStandardMapper standardMapper;
    @Autowired
    private JgCheckContentMapper checkContentMapper;
    @Autowired
    private JgLiabilityScoringMapper liabilityScoringMapper;

    /**
     * 日常检查-保存社会评分信息
     *
     * @param situationData 社会评分记录
     * @param dailyCheck    日常检查
     * @param company       企业信息
     * @param dailySaveVo   异常对象
     */
    public void saveStandardInfo(RectificationSituationData situationData, JgDailyCheck dailyCheck, TcCompany company, DailySaveVo dailySaveVo) {
        List<ItemList> itemList = situationData.getItemList();
        if(itemList.isEmpty()) {
            return;
        }
        Long liabilityTemplateId = dailyCheck.getLiabilityTemplateId();
        double scoreTotal = 0;
        //初始化社会责任评分
        Long scoringId = saveDailyCheckLiabilityScoring(0L, scoreTotal, company, dailyCheck);
        List<JgLiabilityStandard> liabilityStandardList =  liabilityStandardMapper.selectStandardInfoByDailyCheckId(dailyCheck.getId());
        List<Long> itemIdList = itemList.stream().map(ItemList::getId).collect(Collectors.toList());
        List<JgStandard> queryStandartList = standardMapper.selectBatchIds(itemIdList);
        for (ItemList standard : itemList) {
//            JgLiabilityStandard liabilityStandard = liabilityStandardMapper.selectStandardInfo(standard.getId(), dailyCheck.getId(), null);
            Optional<JgLiabilityStandard> liabilityStandardOp = liabilityStandardList.stream().filter(liabilityStandard -> Objects.equals(standard.getId(), liabilityStandard.getStandardId())).findFirst();
            Optional<JgStandard> jgStandardOp = queryStandartList.stream().filter(s -> Objects.equals(s.getId(), standard.getId())).findFirst();// standardMapper.selectById(standard.getId());
            //创建社会标准模版信息
            if (!liabilityStandardOp.isPresent()) {
                Long id = saveLiability(liabilityTemplateId, scoringId, standard.getId(), dailyCheck.getId(), 0L, company, jgStandardOp.orElse(null));
                scoreTotal += saveContentInfo(id, standard.getContentList(), dailySaveVo.getManageStatus());
            } else {
                //修改社会责任评分模版
                scoreTotal += saveContentInfo(liabilityStandardOp.get().getId(), standard.getContentList(), dailySaveVo.getManageStatus());
            }
        }
        saveDailyCheckLiabilityScoring(scoringId, scoreTotal, company, dailyCheck);

    }

    /**
     * 日常检查-保存社会责任评分统计
     *
     * @param scoreId    主键
     * @param scoreTotal 总评分
     * @param company    主体信息
     * @param dailyCheck 日常检查
     * @return id
     */
    public Long saveDailyCheckLiabilityScoring(Long scoreId, Double scoreTotal, TcCompany company, JgDailyCheck dailyCheck) {
        if (scoreId == 0) {
            //统计社会责任评分
            JgLiabilityScoring scoring = new JgLiabilityScoring();
            scoring.setCompanyId(company.getId());
            scoring.setCompanyName(company.getCompanyName());
            scoring.setScoreTotal(scoreTotal);
            scoring.setDailyCheckId(dailyCheck.getId());
            scoring.setDeptId(dailyCheck.getDeptId());
            scoring.setDeptName(dailyCheck.getDeptName());
            scoring.setScoreSource("1");
            scoring.setScorePersonId(dailyCheck.getCheckPerson1Id());
            scoring.setScorePersonName(dailyCheck.getCheckPerson1Name());
            scoring.setScoreYear(new Date());
            scoring.setScoreTime(new Date());
            scoring.setCreateTime(new Date());
            scoring.setCreatorId(dailyCheck.getCreatorId());
            scoring.setCreator(dailyCheck.getCreator());
            scoring.setCreateDeptId(dailyCheck.getCreateDeptId());
            scoring.setCreateDeptName(dailyCheck.getCreateDeptName());
            scoring.setDeleteFlag("0");
            liabilityScoringMapper.insert(scoring);
            return scoring.getId();
        } else {
            JgLiabilityScoring scoring = liabilityScoringMapper.selectById(scoreId);
            scoring.setScoreTotal(scoreTotal);
            liabilityScoringMapper.updateById(scoring);
            return scoring.getId();
        }

    }

    /**
     * 动态评分，保存社会责任评分
     *
     * @param dynamicScoring 动态评分对象
     * @param situationData  社会责任评分内容
     * @param company        主体信息
     * @param manageStatus   起否是生产企业
     */
    public void saveLiabilityStandard(JgDynamicScoring dynamicScoring, RectificationSituationData situationData, TcCompany company, String manageStatus) {

        List<ItemList> itemList = situationData.getItemList();
        double scoreTotal = 0;
        //初始化社会责任总评分信息
        Long scoringId = saveDynamicLiabilityScoring(0L, scoreTotal, company, dynamicScoring);
        if (!itemList.isEmpty()){
            for (ItemList standard : itemList) {
                JgLiabilityStandard liabilityStandard = liabilityStandardMapper.selectStandardInfo(standard.getId(), null, dynamicScoring.getId());
                JgStandard jgStandard = standardMapper.selectById(standard.getId());
                //创建社会标准模版信息
                if (liabilityStandard == null) {
                    Long id = saveLiability(standard.getTemplateId(), scoringId, standard.getId(), 0L, dynamicScoring.getId(), company, jgStandard);
                    scoreTotal += saveContentInfo(id, standard.getContentList(), manageStatus);
                } else {
                    //修改社会责任评分模版
                    scoreTotal += saveContentInfo(liabilityStandard.getId(), standard.getContentList(), manageStatus);
                }

            }
            //更新汇总社会责任总评分
            saveDynamicLiabilityScoring(scoringId, scoreTotal, company, dynamicScoring);
        }


    }

    /**
     * 动态评分-保存社会责任评分统计
     *
     * @param scoreId        主键
     * @param scoreTotal     总评分
     * @param company        主体信息
     * @param dynamicScoring 动态评分
     * @return id
     */
    public Long saveDynamicLiabilityScoring(Long scoreId, Double scoreTotal, TcCompany company, JgDynamicScoring dynamicScoring) {
        //统计社会责任评分
        if (scoreId == 0) {
            JgLiabilityScoring scoring = new JgLiabilityScoring();
            scoring.setCompanyId(company.getId());
            scoring.setCompanyName(company.getCompanyName());
            scoring.setScoreTotal(scoreTotal);
            scoring.setDynamicScoringId(dynamicScoring.getId());
            scoring.setDeptId(dynamicScoring.getDeptId());
            scoring.setDeptName(dynamicScoring.getDeptName());
            scoring.setScorePersonId(dynamicScoring.getScorePerson1Id());
            scoring.setScorePersonName(dynamicScoring.getScorePerson1Name());
            scoring.setScoreYear(new Date());
            scoring.setScoreTime(new Date());
            scoring.setCreateTime(new Date());
            scoring.setScoreSource("2");
            scoring.setCreatorId(dynamicScoring.getCreatorId());
            scoring.setCreator(dynamicScoring.getCreator());
            scoring.setCreateDeptId(dynamicScoring.getCreateDeptId());
            scoring.setCreateDeptName(dynamicScoring.getCreateDeptName());
            scoring.setDeleteFlag("0");
            liabilityScoringMapper.insert(scoring);
            return scoring.getId();
        } else {
            JgLiabilityScoring scoring = liabilityScoringMapper.selectById(scoreId);
            scoring.setScoreTotal(scoreTotal);
            liabilityScoringMapper.updateById(scoring);
            return scoring.getId();
        }
    }

    /**
     * 创建社会评分项目信息
     *
     * @param liabilityTemplateId 社会评分模版id
     * @param standardId          社会评分标准版Id
     * @param checkId             日常检查信息
     * @param company             企业信息
     * @param jgStandard          监管标准
     * @return id
     */

    public Long saveLiability(Long liabilityTemplateId, Long scoringId, Long standardId, Long checkId, Long dynamicScoringId, TcCompany company, JgStandard jgStandard) {
        JgLiabilityStandard newStandard = new JgLiabilityStandard();
        try {
            newStandard.setCompanyId(company.getId());
            newStandard.setCompanyName(company.getCompanyName());
            newStandard.setLiabilityScoringId(scoringId);
            newStandard.setTemplateId(liabilityTemplateId);
            newStandard.setStandardId(standardId);
            newStandard.setSupCategory("4");
            newStandard.setSupProcess(company.getSupProcess());
            newStandard.setSpxsId(jgStandard.getSpxsId());
            newStandard.setCyfwId(jgStandard.getCyfwId());
            newStandard.setSpscLbId(jgStandard.getSpscLbId());
            newStandard.setSpscLbZlId(jgStandard.getSpscLbZlId());
            newStandard.setTsspLbId(jgStandard.getTsspLbId());
            newStandard.setTsspLbZlId(jgStandard.getTsspLbZlId());
            newStandard.setName(jgStandard.getName());
            newStandard.setSerialNum(jgStandard.getSerialNum());
            newStandard.setDailyCheckId(checkId);
            newStandard.setDynamicScoringId(dynamicScoringId);
            newStandard.setCreateTime(new Date());
            newStandard.setCreatorId(UserHelper.getUserId());
            newStandard.setCreator(UserHelper.getUserInfo().getName());
            newStandard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
            newStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
            newStandard.setDeleteFlag(0L);
            log.info("新增liabilityStandard:{}", newStandard.toString());
            liabilityStandardMapper.insert(newStandard);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存社会评分检查内容大项失败!");
        }

        return newStandard.getId();
    }

    /**
     * 保存社会评分项内容
     *
     * @param liabilityId  评分项ID
     * @param contentList  评分项列表
     * @param manageStatus 状态
     */
    public Double saveContentInfo(Long liabilityId, List<ContentList> contentList, String manageStatus) {
        double scoreTotal = 0;
        try {
            List<JgLiabilityContent> liabilityContentList  = contentMapper.selectByLiabilityId(liabilityId);
            List<Long> contentIdList = contentList.stream().map(ContentList::getId).collect(Collectors.toList());
            List<JgCheckContent> queryCheckContentList = checkContentMapper.selectBatchIds(contentIdList);

            if (!contentList.isEmpty() && liabilityId > 0) {
                // 预构建 existingLiabilityContents 的映射（contentId → JgLiabilityContent）
                Map<Long, JgLiabilityContent> existingLiabilityMap = liabilityContentList.stream()
                        .collect(Collectors.toMap(
                                JgLiabilityContent::getContentId,
                                Function.identity()
                        ));

                // 预构建 contentQueryMap 用于快速查询
                Map<Long, JgCheckContent> contentQueryMap = queryCheckContentList.stream()
                        .collect(Collectors.toMap(
                                JgCheckContent::getId,
                                Function.identity()
                        ));

                // 收集需要插入和更新的对象
                List<JgLiabilityContent> insertList = new ArrayList<>();
                List<JgLiabilityContent> updateList = new ArrayList<>();

                for (ContentList content : contentList) {
                    JgCheckContent contentQuery = contentQueryMap.get(content.getId());
                    if (contentQuery == null) {
                        throw new RuntimeException("检查内容小项不存在: " + content.getId());
                    }

                    JgLiabilityContent liabilityContent;
                    if (!existingLiabilityMap.containsKey(content.getId())) {
                        // 创建新的对象
                        liabilityContent = new JgLiabilityContent();
                        liabilityContent.setContentId(content.getId());
                        liabilityContent.setLiabilityStandardId(liabilityId);
                        liabilityContent.setCreateTime(new Date());
                        liabilityContent.setCreatorId(UserHelper.getUserId());
                        liabilityContent.setCreator(UserHelper.getUserInfo().getName());
                        liabilityContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                        liabilityContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                        liabilityContent.setDeleteFlag(0L);
                        insertList.add(liabilityContent);
                    } else {
                        // 获取已有对象
                        liabilityContent = existingLiabilityMap.get(content.getId());
                        updateList.add(liabilityContent);
                    }

                    // 公共字段设置（无论新增还是更新）
                    liabilityContent.setCheckContent(content.getCheckContent());
                    liabilityContent.setImportentItem(content.getImportentItem());
                    liabilityContent.setSerialNum(content.getSerialNum() != null ? content.getSerialNum().intValue() : 0);
                    liabilityContent.setMissingItem(content.getMissingItem());
                    liabilityContent.setRemark(contentQuery.getRemark());
                    liabilityContent.setSelection("1".equals(manageStatus) ? "2" : content.getSelection());
                    liabilityContent.setMissingItemContent(content.getMissingItemContent());
                    liabilityContent.setProblemContent(content.getProblemContent());
                    liabilityContent.setProblemContentInput(content.getProblemContentInput());
                    liabilityContent.setMissingItemContentInput(content.getMissingItemContentInput());

                    // 处理分数累加
                    if ("2".equals(content.getSelection())) {
                        double score = contentQuery.getScore() != null ? contentQuery.getScore() : 0;
                        scoreTotal += score;
                        liabilityContent.setScore(score);
                    } else {
                        liabilityContent.setScore(0.0);
                    }
                }

                // 批量操作
                if (!insertList.isEmpty()) {
                    contentMapper.batchInsert(insertList);  // 批量插入
                }
                if (!updateList.isEmpty()) {
                    contentMapper.batchUpdate(updateList);   // 批量更新
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("保存检查内容小项失败!");
        }
        return scoreTotal;
    }

}
